package com.weapons.week0903_weapons.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.gson.Gson;
import com.weapons.week0903_weapons.R;
import com.weapons.week0903_weapons.activity.RecommendContentActivity;
import com.weapons.week0903_weapons.adapter.RecommendListAdapter;
import com.weapons.week0903_weapons.bean.RecommentBean;
import com.weapons.week0903_weapons.constant.UrlString;
import com.weapons.week0903_weapons.view.RecommentTopView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * author:DotaWang
 * time:2016/7/19 19:52
 */
public class RecommendFragment extends Fragment {
    private Activity mActivity;
    private String mpos = "";
    private RecyclerView mRvLists;
    private List<RecommentBean.ItemBean> item;
    private List<RecommentBean.SlideBean> slide;
    private RecommendListAdapter adapter;
    private int i = 1;
    private PtrFrameLayout ptr_refresh;
    private RecommentTopView topView;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = getActivity();
        item = new ArrayList<>();
        slide = new ArrayList<>();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_recommend, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        ptr_refresh = (PtrFrameLayout) view.findViewById(R.id.ptr_refresh);
       /* ptr_refresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptr_refresh.autoRefresh();
            }
        }, 500);*/
        mRvLists = (RecyclerView) view.findViewById(R.id.rv_lists);
        super.onViewCreated(view, savedInstanceState);
        getData(String.format(UrlString.URL_RECOMMEND, String.valueOf(i)));
        adapter = new RecommendListAdapter(mActivity, item);
        final LinearLayoutManager manager = new LinearLayoutManager(mActivity);
        topView = new RecommentTopView(mActivity);
        adapter.addHeadView(topView);
        mRvLists.setAdapter(adapter);
        mRvLists.setLayoutManager(manager);
        adapter.setOnItemClickListener(new RecommendListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int pos, View itemView) {
                Intent intent = new Intent(mActivity, RecommendContentActivity.class);
                intent.putExtra("url", String.format(UrlString.URL_RECOMMEND_CONTENT, item.get(pos-1).getAid()));
                startActivity(intent);
            }
        });
        mRvLists.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisiableItemPosition = manager.findLastVisibleItemPosition();
                if (lastVisiableItemPosition + 1 == adapter.getItemCount()) {
                    i++;
                    getData(String.format(UrlString.URL_RECOMMEND, String.valueOf(i)));
                }
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
        });
        ptr_refresh.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
              /*  item.clear();
                slide.clear();
                getData(String.format(UrlString.URL_RECOMMEND, String.valueOf(1)));
                ptr_refresh.refreshComplete();*/
               ptr_refresh.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ptr_refresh.refreshComplete();
                    }
                }, 300);
            }
        });
    }

    public void bte_set1(View view) {
        Toast.makeText(mActivity, "点击", Toast.LENGTH_SHORT).show();
    }

    private void getData(String url) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mActivity, "网络异常，请重试", Toast.LENGTH_SHORT).show();
                    }
                });

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String result = response.body().string();
                final RecommentBean recommentBean = new Gson().fromJson(result, RecommentBean.class);
                item.addAll(recommentBean.getItem());
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("bbbbbb" + i);
                        if (i == 1) {
                           // System.out.println("bbbbbbb" + slide.size());
                           // ptr_refresh.refreshComplete();
                            slide.addAll(recommentBean.getSlide());
                            topView.setData(slide);
                           // System.out.println("bbbbbbb" + slide.size());
                        } /*else {
                            ptr_refresh.refreshComplete();
                        }*/
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        });

    }
}
